<template>
  <template v-if="pure">
    <div class="bind__wecaht">
      <wechat-login
        :loading="wechat.loading"
        :href="wechat.href"
        :state="wechat.state"
        :appid="wechat.appid"
        :scope="wechat.scope"
        :redirect-uri="wechat.redirectUri"
        :timestamp="wechat.timestap"
        height="120px"
        :self-redirect="true"
        @refresh="refresh"
      />
      <p class="text-muted mt10 text-center fs-14" style="margin-bottom: 25px">
        绑定微信快捷登录
      </p>
    </div>
  </template>
  <el-dialog v-else v-model="showWxChat" width="320px" :align-center="true" :close-on-click-modal="false">
    <div class="bind__wecaht">
      <h2>绑定微信</h2>
      <div class="tips" v-if="bindStatus===bindStatusMap.testAuth">
        绑定中
      </div>
      <div class="tips" v-else-if="bindStatus===bindStatusMap.success">
        绑定成功
      </div>
      <div class="tips" v-else-if="bindStatus===bindStatusMap.fail">
        绑定失败
      </div>
      <wechat-login v-else
        :loading="wechat.loading"
        :href="wechat.href"
        :state="wechat.state"
        :appid="wechat.appid"
        :scope="wechat.scope"
        :redirect-uri="wechat.redirectUri"
        :self-redirect="true"
        :timestamp="wechat.timestap"
        height="120px"
        @refresh="refresh"
      />
      <p class="text-muted mt10 text-center fs-14" style="margin-bottom: 25px">
        绑定微信快捷登录
      </p>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import WechatLogin from "@/components/wechat-bind-code/index.vue";
import { getPartyParam, bindAuth } from "@/api/login";
import { userAppStore } from "@/stores/user";
import { systemAppStore } from "@/stores/system";
import PsMessage from "@/components/message/index";
import PsMessageBox from "@/components/message-box/index";
import { invokeAPi } from "@/xz-fn";
export interface Props {
  pure?: boolean;
  from?: "anymouse" | "member";
}
const props = defineProps<Props>();

const _systemAppStore_ = systemAppStore();
const _userAppStore_ = userAppStore();
const router = useRouter();
const showWxChat = ref(false);
const bindStatusMap = {
  "waitAuth": "waitAuth",
  "testAuth": "testAuth",
  "success": "success",
  "fail": "fail",
};
const bindStatus = ref(bindStatusMap.waitAuth);
const wechat = reactive({
  loading: true,
  href: "data:text/css;base64,LmltcG93ZXJCb3h7CiAgICBsaW5lLWhlaWdodDogMTsKfQoKLmltcG93ZXJCb3ggLnRpdGxlLAouaW1wb3dlckJveCAuaW5mbywKLnN0YXR1c19pY29uLAouaW1wb3dlckJveCAuc3RhdHVzIHtkaXNwbGF5OiBub25lO30KCi5pbXBvd2VyQm94IC5xcmNvZGUgewogICAgd2lkdGg6IDE2MHB4OwogICAgaGVpZ2h0OiAxNjBweDsKICAgIGJvcmRlcjogMDsKICAgIG1hcmdpbi10b3A6IDA7Cn0=",
  state: "qekjdsbkje893214wechat",
  appid: "",
  scope: "",
  redirectUri:  encodeURI(import.meta.env.VITE_APP_CB_ORIGIN + '/party-login-cb.html?type=BindWxLoginFinish&skipInit=1'),
  style: "black",
  timestap: 0
});

export interface BindWechatApi {
  open: () => void;
}

const getWxParam = () => {
  getPartyParam({ type: "wx" })
    .then((res: any) => {
      wechat.appid = res?.data.appid;
      wechat.scope = res?.data.scope;
    })
    .finally(() => {
      wechat.loading = false;
    })
};

const refresh = () => {
  getWxParam();
};

const open = () => {
  showWxChat.value = true;
  wechat.loading = true;
  bindStatus.value = bindStatusMap.waitAuth;
  getWxParam();
};

const handleBindWechat = (param: any) => {
  bindStatus.value = bindStatusMap.testAuth;
  const params = {
    auth_type: "wx", // phone-绑定手机,wx-绑定微信
    phone: "", // 手机号码,auth_type=phone为必填
    auth_code: param.code, // 授权码或者手机验证码
    code_id: "", // 手机验证码对应id,只有授权类型为phone需要
    bind_type: 0, // 0-绑定，1-换绑
    old_phone: "",
    old_auth_code: "",
    old_code_id: ""
  };
  bindAuth(params)
    .then((res: any) => {
      if (!res.data.need_merge) {
        _userAppStore_.getUserInfo();
        PsMessage("绑定成功");
        invokeAPi('fq_NotifyWebMessageEx', '', {
          action: 'bindSuccess'
        })
        bindStatus.value = bindStatusMap.success;
        showWxChat.value = false;
      }else{
        PsMessageBox.confirm("该账号已注册登录过，不支持绑定", {
          confirmButtonText: "关闭",
          cancelButtonText: "提交反馈",
          distinguishCancelAndClose: true,
          callback: (action: string) => {
            if (action === "cancel") {
              router.push("/feedback");
            }
          }
        });
        return Promise.reject(res);
      }
    })
    .catch(() => {
      bindStatus.value = bindStatusMap.waitAuth;
    })
};
function onMessage(msg:any) {
  if(msg.data?.type === "BindWxLoginFinish" && msg.data.code){
    handleBindWechat({ code: msg.data.code });
  }
}
defineExpose<BindWechatApi>({
  open
});

onMounted(() => {
  window.addEventListener("message", onMessage);
});
onUnmounted(() => {
  window.removeEventListener("message", onMessage);
});
</script>

<style lang="scss" scoped>
h2 {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  padding-bottom: 20px;
  color: var(--el-text-color-primary);
}
.tips{
  margin: 0 auto;
  width: 160px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: var(--el-text-color-regular);
}
</style>
